<template>
    <div id="channel-home">
        <Feedback :isSuccess="isSuccess" :isError="isError" :text="text"></Feedback>
        <div class="nav-bgcolor" style="height: 500px;">
            <div id="channel-header">
                <v-container class="py-0">
                    <v-row class="justify-space-between">
                        <v-btn class="ma-2" click :to="`/channels/${this.channel.userId}`">
                            <v-icon>mdi-arrow-left</v-icon> 返回
                        </v-btn>
                        <v-skeleton-loader type="list-item-avatar-two-line" :loading="loading" class="mr-1">
                            <v-card class="transparent" flat>
                                <v-list-item three-line>
                                    <v-list-item-avatar size="50">
                                        <v-img v-if="channel.avatar !== 'no-photo.jpg'" :src="channel.avatar"></v-img>
                                        <v-avatar v-else color="red" size="60">
                                            <span class="white--text headline ">
                                                {{
                                                    channel.nickName.split('')[0].toUpperCase()
                                                }}</span>
                                        </v-avatar>
                                    </v-list-item-avatar>
                                    <v-list-item-content class="align-self-auto">
                                        <v-list-item-title class="h3 mb-1">{{
                                            channel.nickName
                                            }}</v-list-item-title>
                                        <v-list-item-title style="margin-top: 10px;">{{
                                            channel.personalSignature
                                            }}</v-list-item-title>
                                    </v-list-item-content>
                                </v-list-item>
                            </v-card>
                        </v-skeleton-loader>
                        <v-col cols="12" sm="5" md="3" lg="3" v-if="!loading">
                            <v-btn v-if="currentUser && channel.userId !== currentUser.userId" :class="[
                                { 'red white--text': !subscribed },
                                { 'grey grey--text lighten-3 text--darken-3': subscribed },
                                'mt-6'
                            ]" tile large depressed :loading="subscribeLoading" @click="subscribe">{{ !subscribed ?
                                '关注' : '已关注'
                                }}</v-btn>
                            <!-- <template v-else-if="!currentUser" -->
                            <v-btn v-else-if="showSubBtn" :class="[
                                { 'red white--text': !subscribed },
                                { 'grey grey--text lighten-3 text--darken-3': subscribed },
                                'mt-6'
                            ]" tile large depressed :loading="subscribeLoading" @click="subscribe">{{ !subscribed ?
                                '关注' : '已关注'
                                }}</v-btn>
                            <!-- <v-btn icon class="ml-5 mt-6"><v-icon>mdi-bell</v-icon></v-btn> -->
                        </v-col>
                    </v-row>
                    <v-divider></v-divider>
                    <div style="height: 500px; overflow-y: scroll;">
                        <div v-for="message in messageList" :key="message"
                            :style="message.userId == channel.userId ? 'display: flex; flex-direction: row-reverse;' : ''">
                            <div>
                                <v-chip v-if="message.userId == channel.userId" color="primary">
                                    {{ message.message }}
                                </v-chip>
                                <v-list-item-avatar size="40" v-if="message.userId == channel.userId">
                                    <v-img v-if="currentUser.avatar !== 'no-photo.jpg'"
                                        :src="currentUser.avatar"></v-img>
                                    <v-avatar v-else color="red" size="60">
                                        <span class="white--text headline ">
                                            {{
                                                currentUser.nickName.split('')[0].toUpperCase()
                                            }}</span>
                                    </v-avatar>
                                </v-list-item-avatar>
                                <v-list-item-avatar size="40" v-if="message.userId == currentUser.userId">
                                    <v-img v-if="channel.avatar !== 'no-photo.jpg'" :src="channel.avatar"></v-img>
                                    <v-avatar v-else color="red" size="60">
                                        <span class="white--text headline ">
                                            {{
                                                channel.nickName.split('')[0].toUpperCase()
                                            }}</span>
                                    </v-avatar>
                                </v-list-item-avatar>
                                <v-chip v-if="message.userId == currentUser.userId">
                                    {{ message.message }}
                                </v-chip>
                            </div>
                        </div>
                    </div>
                    <v-row class="justify-space-between">
                        <v-text-field v-model="message" label="消息" class="mb-3" outlined dense></v-text-field>
                        <v-btn class="primary" @click="sendMessage" style="margin-left: 10px;" depressed>发送</v-btn>
                    </v-row>
                </v-container>

            </div>
        </div>
        <signin-modal :openModal="signinDialog" :details="details" @closeModal="signinDialog = false" />
    </div>

</template>
<script>
import { mapGetters } from 'vuex'


import SigninModal from '@/components/SigninModal'
import { checkFollowing, following, getUserById } from '../../services/UserRequest';
import Feedback from '../../components/Feedback.vue';
export default {
    data: () => ({
        socket: null,
        messageList: [],
        message: '',
        tab: null,
        loading: false,
        errored: false,
        subscribed: false,
        subscribeLoading: false,
        showSubBtn: true,
        items: ['主页', '视频', '社区'],
        videos: {},
        channel: {},
        signinDialog: false,
        details: {},
        text: '',
        isError:false,
        isSuccess:false
    }),
    watch: {
        isError() {
            if (this.isError) {
                setTimeout(() => {
                    this.isError = false
                }, 3000)
            }
        },
        isSuccess() {
            if (this.isSuccess) {
                setTimeout(() => {
                    this.isSuccess = false
                }, 3000)
            }
        }
    },
    computed: {
        ...mapGetters(['isAuthenticated', 'currentUser'])
    },
    components: {
        SigninModal,
        Feedback
    },
    methods: {
        sendMessage() {
            if (this.socket.readyState === WebSocket.OPEN) {
                const info = {
                    userId: this.channel.userId,
                    message: this.message
                }
                this.socket.send(JSON.stringify(info));
                this.messageList.push(info)
                this.message = ''
                console.log('消息已发送:', this.message)
            } else {
                console.log('WebSocket连接未打开，无法发送消息')
            }
        },
        // initWebSocket() {
        //     const webSocket = new WebSocket("ws://127.0.0.1:8080/chat", [localStorage.getItem("Authorization")])
        //     this.webSocket = webSocket
        //     this.webSocket.onopen = webSocket.onopen;
        //     this.webSocket.onerror = webSocket.onerror;
        //     this.webSocket.onmessage = webSocket.onmessage
        //     this.webSocket.onclose = webSocket.onclose;
        //     this.webSocket.send = webSocket.send
        //     this.tryToConnect()
        // },
        // tryToConnect() {
        //     this.webSocket.onopen = function () {
        //         console.log('连接成功');
        //         this.webSocket.send(JSON.stringify({
        //             userId: this.$route.params.id,
        //             message: this.message
        //         }))
        //     }
        //     this.webSocket.onmessage = function (event) {
        //         console.log(event.data)
        //         const data = JSON.parse(event.data)
        //         console.log(data)
        //         let cacheMessage = data
        //         this.messageList.push(cacheMessage)
        //         console.log(this.messageList)
        //     }
        // },
        async getChannel(id) {
            // console.log(this.$route.params.id)
            this.loading = true
            this.errored = false

            const channel = await getUserById(id)
                .catch((err) => {
                    this.errored = true
                    console.log(err)
                    this.$router.push('/')
                })
                .finally(() => (this.loading = false))

            if (!channel) return
            this.channel = channel.data.data
            // console.log(channel)
            if (this.currentUser && this.currentUser.userId === this.channel.userId) {
                this.showSubBtn = false
            } else {
                this.showSubBtn = true
            }
            this.checkSubscription(this.channel.userId)
            // console.log(channel)
        },
        async checkSubscription(id) {
            if (!this.currentUser) return
            this.loading = true
            const sub = await checkFollowing(id)
                .catch((err) => {
                    console.log(err)
                })
                .finally(() => {
                    this.loading = false
                })
            // console.log(sub.data.data)
            if (!sub) return

            if (!sub.data.data) this.subscribed = false
            else this.subscribed = true
        },
        async subscribe() {
            if (!this.isAuthenticated) {
                this.signinDialog = true
                this.details = {
                    title: '想要更多关于该博主的视频？',
                    text: '登录即可关注该博主'
                }
                return
            }
            this.subscribeLoading = true
            const sub = await following(this.channel.userId)
                .catch((err) => console.log(err))
                .finally(() => {
                    this.subscribeLoading = false
                })

            if (!sub) return

            this.subscribed = !this.subscribed
            if (this.subscribed) {
                this.video.fansCount++
            } else {
                this.video.fansCount--
            }

            // console.log(this.subscribed)
        }
    },
    mounted() {
        this.getChannel(this.$route.params.id)
        this.socket = new WebSocket('ws://127.0.0.1:8080/chat', [localStorage.getItem("Authorization")]);
        this.socket.onopen = () => {
            console.log('WebSocket连接已打开');
            const cache = {
                userId: this.$route.params.id,
                message: ''
            }
            console.log(cache)
            console.log(JSON.stringify(cache))
            this.socket.send(JSON.stringify(cache))
        };
        this.socket.onmessage = (event) => {
            console.log(event.data.charAt(0))
            if (event.data.charAt(0) == "{") {
                let cacheMessage = JSON.parse(event.data)

                if (cacheMessage && cacheMessage.message != '') {
                    this.messageList.push(cacheMessage)
                }
            }else{
                this.text = event.data
                this.isSuccess = true
            }
        };
        this.socket.onclose = (event) => {
            console.log(event)
            console.log('WebSocket连接已关闭');
        };
    },
    beforeRouteUpdate(to, from, next) {
        console.log(from)
        this.getChannel(to.params.id)
        next()
    }
}
</script>